import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import type { Irecord } from '@/types/types'
type Idata = {
  name: string
  value: number | string
}
export const useRecordStore = defineStore('record', () => {
  const inCome = ref<Irecord[]>([])
  const outCome = ref<Irecord[]>([])
  const totalCome = ref<Irecord[]>([])

  function generateRandomId(): string {
    return Math.random().toString(36).substring(2, 10)
  }
  function setData(data: Idata, flag: boolean) {
    const newdata = {
      id: generateRandomId(),
      name: data.name,
      value: data.value,
      time: new Date().toLocaleString()
    }
    totalCome.value.push(newdata)
    if (flag) {
      inCome.value.push(newdata)
    } else {
      outCome.value.push({
        ...newdata,
        value: -data.value
      })
    }
  }
  const numData = computed(() => {
    const inmoney = inCome.value.reduce((acc, cur) => {
      return acc + Number(cur.value)
    }, 0)
    const outmoney = outCome.value.reduce((acc, cur) => {
      return acc + Number(cur.value)
    }, 0)
    return {
      inmoney,
      outmoney,
      total: inmoney - outmoney
    }
  })
  function deleteData(id: string) {
    totalCome.value = totalCome.value.filter((item) => item.id !== id)
    inCome.value = inCome.value.filter((item) => item.id !== id)
    outCome.value = outCome.value.filter((item) => item.id !== id)
  }

  return { inCome, outCome, totalCome, setData, deleteData,numData }
})
